package com.itheima.web.controller.system;


import com.itheima.core.BaseServlet;
import com.itheima.domain.system.Module;
import com.itheima.service.system.ModuleService;
import com.itheima.service.system.impl.ModuleServiceImpl;
import com.itheima.utils.BeanUtil;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@WebServlet("/system/module/*")
public class Moduleservlet extends BaseServlet {
    private ModuleService moduleService = new ModuleServiceImpl();

    public String list(HttpServletRequest request, HttpServletResponse response) throws Exception{

        String pageNum = request.getParameter("pageNum");
        String pageSize = request.getParameter("pageSize");

        if(StringUtil.isEmpty(pageNum)){
            pageNum = "1";
        }
        if(StringUtil.isEmpty(pageSize)){
            pageSize = "5";
        }

        PageInfo<Module> pageInfo = moduleService.queryPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize));

        request.setAttribute("page",pageInfo);

        return "/WEB-INF/pages/system/module/list.jsp";
    }

    public String toEdit(HttpServletRequest request, HttpServletResponse response) throws Exception{
        String id = request.getParameter("id");

        Module module = moduleService.findById(id);
        List<Module> modules = moduleService.findAll();

        request.setAttribute("module",module);
        request.setAttribute("moduleList",modules);
        return "/WEB-INF/pages/system/module/update.jsp";

    }

    public String edit(HttpServletRequest request, HttpServletResponse response) throws Exception{
        Module module = BeanUtil.fillBean(request, Module.class, "yyyy-MM-dd");

        moduleService.update(module);

        return  "/system/module/list";
    }


    public String toAdd(HttpServletRequest request, HttpServletResponse response) throws Exception{
        List<Module> modules = moduleService.findAll();
        request.setAttribute("moduleList",modules);
        return  "/WEB-INF/pages/system/module/add.jsp";
    }

    public String save(HttpServletRequest request, HttpServletResponse response) throws Exception{
        Module module = BeanUtil.fillBean(request, Module.class, "yyyy-MM-dd");

        moduleService.save(module);

        return  "/system/module/list";
    }

    public String delete(HttpServletRequest request, HttpServletResponse response) throws Exception{
        String[] ids = request.getParameterValues("id");

        moduleService.deleteById(ids);

        return  "/system/module/list";
    }
}
